<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * ContactForm is the model behind the contact form.
 */
class ContactForm extends Model
{
    // 联系人名称
    public string $name = "";
    // 联系人邮箱
    public string $email = "";
    // 邮件主题
    public string $subject = "";
    // 邮件内容
    public string $body = "";
    // 邮件验证码
    public string $verifyCode = "";


    /**
     * @return array 校验规则.
     */
    public function rules(): array
    {
        return [
            // name, email, subject and body 是必须输入的
            [['name', 'email', 'subject', 'body'], 'required'],
            // 电子邮件必须是有效的电子邮件地址
            ['email', 'email'],
            // 验证码需要正确输入
            ['verifyCode', 'captcha'],
        ];
    }

    /**
     * @return array 自定义属性标签
     */
    public function attributeLabels(): array
    {
        return [
            'verifyCode' => '验证码',
            'name' => '名字',
            'email' => '邮箱',
            'subject' => '主体',
            'body' => '内容'
        ];
    }

    /**
     * 使用此模型收集的信息向指定的电子邮件地址发送电子邮件.
     * @param string $email 目标电子邮件地址
     * @return bool 模型是否通过验证
     */
    public function contact(string $email): bool
    {
        if ($this->validate()) {
            Yii::$app->mailer->compose()
                ->setTo($email)
                ->setFrom([Yii::$app->params['senderEmail'] => Yii::$app->params['senderName']])
                ->setReplyTo([$this->email => $this->name])
                ->setSubject($this->subject)
                ->setTextBody($this->body)
                ->send();

            return true;
        }
        return false;
    }
}
